<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>

<th:block th:fragment="config">

    <div class="config-section" id="detail_conf" v-cloak>
        <h5 class="section-title">通用设置</h5>
        <div class="config-content">

        <!-- 欢迎语设置-->
        <div class="config-card box-border">
            <div class="card-header">欢迎语设置</div>
            <div class="card-body p-4 box-border">
                <div class="mb-4">
                    <label class="form-label">欢迎语</label>
                    <el-input type="textarea" class="form-control" rows="3" v-model="config_form.welcomeMsg"></el-input>
                </div>
                
                <!-- 开场问题设置 -->
                <div class="mb-0">
                    <div class="opening-questions-header flex">
                        <label class="form-label">开场问题</label>
                        <span class="info-icon">?
                            <div class="tooltip">
                                开启后会在欢迎语后按顺序显示所有开场问题。
                            </div>
                        </span>
                    </div>
                    <div class="mb-3 flex items-center">
                        <el-switch 
                            v-model="config_form.openingQuestionsEnabled"
                            @change="handleOpeningQuestionsToggle"
                            :active-value="true"
                            :inactive-value="false">
                        </el-switch>
                        <span class="ml-2 text-sm text-gray-600">启用开场问题</span>
                    </div>
                    
                    <!-- 开场问题输入区域 -->
                    <div v-show="config_form.openingQuestionsEnabled" class="opening-questions-inputs">
                        <template v-for="(question, index) in config_form.openingQuestions" :key="'question-' + index">
                            <div class="mb-3">
                                <div class="flex items-center">
                                    <el-input 
                                        v-model="config_form.openingQuestions[index]"
                                        :placeholder="'开场问题 ' + (index + 1)"
                                        class="flex-1"
                                        clearable>
                                    </el-input>
                                    <el-button 
                                        v-if="config_form.openingQuestions.length > 1"
                                        @click="removeOpeningQuestion(index)"
                                        type="danger" 
                                        icon="el-icon-delete" 
                                        size="small" 
                                        class="ml-2">
                                    </el-button>
                                </div>
                            </div>
                        </template>
                        
                        <!-- 添加问题按钮 -->
                        <el-button 
                            v-if="config_form.openingQuestions.length < 3"
                            @click="addOpeningQuestion"
                            type="primary" 
                            icon="el-icon-plus" 
                            size="small" 
                            plain>
                            添加问题
                        </el-button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 模型配置卡片 -->
        <div class="config-card box-border">
            <div class="card-header flex">
                <div class="flex-1">模型配置</div>
                <div class="toggle-arrow flex items-center mt-2" @click="toggleModelConfig">
                    <i :class="isModelConfigExpanded ? 'el-icon-arrow-down' : 'el-icon-arrow-right'"></i>
                </div>
            </div>
            <div class="card-body p-4 box-border" v-show="isModelConfigExpanded">
                <!-- 模型选择 -->
                <div class="mb-4">
                    <label class="form-label">模型选择</label>
                    <el-select class="model-select border border-gray-300 w-full round-lg"
                               v-model="config_form.aiModelId" placeholder="请选择">
                        <!-- 按类别分组-->
                        <el-option-group v-for="(value, key, index) in config_modelGroupList" :label="key">
                            <!-- 动态加载的选项-->
                            <el-option v-for="(model,index1) in value" :label="model.modelName"
                                       :value="model.id">
                                <div class="model-option-content">
                                    <span class="model-name">{{model.modelName}}</span>
                                    <span class="model-capability-icons" v-if="getModelCapabilityIcons(model).length > 0">
                                        <span 
                                            v-for="icon in getModelCapabilityIcons(model)"
                                            :key="icon.key"
                                            :class="['capability-icon', icon.class]"
                                            :title="icon.tooltip"
                                            @mouseenter="showTooltip($event)"
                                            @mouseleave="hideTooltip($event)">
                                            <i :class="icon.icon"></i>
                                        </span>
                                    </span>
                                </div>
                            </el-option>
                        </el-option-group>
                    </el-select>
                    <!--<small class="text-muted">每次对话消耗会话次数：1次</small>-->
                </div>

                <!-- 语音输入-->
                <div class="mb-4 flex">
                    <div class="voice-input flex flex-1">
                        <label class="form-label">语音输入</label>
                        <span class="info-icon">?
                            <div class="tooltip">
                                开启后，用户在分享页能够进行语音输入
                            </div>
                        </span>
                    </div>
                    <div class="flex-4 items-center mt-2">
                        <el-switch class="ml-[10px]"
                                   v-model="config_form.aiConfig.voiceInputStatus"
                                   @change="handleSwitchChange"
                                   :active-value="1"
                                   :inactive-value="0">
                        </el-switch>
                    </div>
                </div>

                <!-- 连续对话-->
                <div class="mb-4">
                    <div class="multi-turn flex">
                        <label class="form-label">连续对话</label>
                        <span class="info-icon">?
                            <div class="tooltip">
                                设置带入模型上下文的对话历史轮数。轮数越多，多轮对话的相关性越高，但消耗的Token也越多。
                            </div>
                        </span>
                    </div>
                    <div class="flex items-center mt-2">
                        <el-slider
                                v-model="config_form.aiConfig.dialogsNum"
                                :min="1"
                                :max="100"
                                @change="handleSliderChange"
                                show-input
                                input-size="small"
                                class="flex-1">
                        </el-slider>
                    </div>
                </div>

                <!-- 角色设置 -->
                <div class="mb-0">
                    <label class="form-label">角色设置</label>
                    <el-input type="textarea" v-model="config_form.aiSysPromptText" class="form-control sysPrompt"

                              placeholder="你将为AI设置一个角色，从而控制对话的方向，默认为'你是一个有用的帮手'"></el-input>
                </div>
            </div>
        </div>

        <!-- 插件组配置卡片-->
        <div class="config-card box-border">
            <div class="card-header flex">
                <div class="flex-1">
                    <span>插件组配置</span>
                    <el-badge :value="addedPluginGroups.length" :hidden="addedPluginGroups.length === 0" class="plugin-group-count-badge">
                    </el-badge>
                </div>
                <div class="toggle-arrow flex items-center mt-2" @click="togglePluginGroupConfig">
                    <i :class="isPluginGroupConfigExpanded ? 'el-icon-arrow-down' : 'el-icon-arrow-right'"></i>
                </div>
            </div>
            <div class="card-body p-4 box-border" v-show="isPluginGroupConfigExpanded">
                <!-- 已添加的插件组列表 -->
                <div class="added-plugin-groups-section" v-if="addedPluginGroups.length > 0">
                    <h6 class="section-subtitle">已添加插件组 ({{addedPluginGroups.length}})</h6>
                    <div class="added-plugin-groups-grid">
                        <div class="added-plugin-group-item" v-for="(group, index) in addedPluginGroups" :key="index" :class="'plugin-group-type-' + group.groupType">
                            <div class="plugin-group-item-header">
                                <div class="plugin-group-item-icon" :class="'plugin-group-icon-type-' + group.groupType">
                                    <i :class="getPluginGroupIcon(group.groupType)"></i>
                                </div>
                                <div class="plugin-group-item-actions">
                                    <el-dropdown trigger="click" @command="handlePluginGroupAction">
                                        <el-button type="text" size="mini" class="plugin-group-menu-btn">
                                            <i class="el-icon-more"></i>
                                        </el-button>
                                        <el-dropdown-menu slot="dropdown">
                                            <el-dropdown-item :command="{action: 'config', group: group}">
                                                <i class="el-icon-setting"></i> 配置
                                            </el-dropdown-item>
                                            <el-dropdown-item :command="{action: 'delete', group: group}" class="danger-item">
                                                <i class="el-icon-delete"></i> 移除
                                            </el-dropdown-item>
                                        </el-dropdown-menu>
                                    </el-dropdown>
                                </div>
                            </div>
                            <div class="plugin-group-item-body">
                                <h5 class="plugin-group-item-name">{{group.groupName}}</h5>
                                <p class="plugin-group-item-desc">{{group.groupDesc || '暂无描述'}}</p>
                                <div class="plugin-group-item-meta">
                                    <el-tag size="mini" :type="getPluginGroupTypeTagType(group.groupType)" class="plugin-group-type-tag">
                                        {{group.groupTypeName}}
                                    </el-tag>
                                    <span class="plugin-group-plugins-count">
                                        <i class="el-icon-collection"></i> 
                                        {{group.plugins ? group.plugins.length : 0}} 个插件
                                    </span>
                                    <span class="plugin-group-priority">
                                        <i class="el-icon-sort"></i> 
                                        优先级: {{group.priority || 0}}
                                    </span>
                                </div>
                                <!-- 插件组内插件预览 -->
                                <div class="plugin-group-plugins-preview" v-if="group.plugins && group.plugins.length > 0">
                                    <div class="plugins-preview-title">包含插件:</div>
                                    <div class="plugins-preview-list">
                                        <span class="plugin-preview-item" 
                                              v-for="(plugin, pidx) in group.plugins.slice(0, 3)" 
                                              :key="pidx"
                                              :title="plugin.pluginName + ' - ' + plugin.pluginDesc">
                                            {{plugin.pluginLabel || plugin.pluginName}}
                                        </span>
                                        <span class="plugin-preview-more" v-if="group.plugins.length > 3">
                                            +{{group.plugins.length - 3}}
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 添加插件组按钮 -->
                <div class="add-plugin-group-section">
                    <h6 class="section-subtitle" v-if="addedPluginGroups.length > 0">添加更多插件组</h6>
                    <div class="add-plugin-group-button" @click="handleAddPluginGroupOne">
                        <div class="add-plugin-group-icon">
                            <i class="el-icon-plus"></i>
                        </div>
                        <div class="add-plugin-group-text">
                            <h5>添加插件组</h5>
                            <p>为智能体添加功能插件组，一次性获得多个相关插件</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>


        <!-- 高级设置按钮（独立于卡片之外） -->
        <div class="advanced-toggle-btn text-right" @click="toggleAdvancedSettings">
            <el-button class="px-[15px] py-[10px]" type="text">
                <span>高级设置</span>
                <i class="el-icon-arrow-down" v-if="showAdvancedSettings"></i>
                <i class="el-icon-arrow-up" v-else></i>
            </el-button>
        </div>

        <!-- 高级功能卡片 （初始隐藏） -->
        <div class="config-card box-border  advanced-settings-card" v-show="showAdvancedSettings">
            <div class="card-header">API配置</div>
            <div class="card-body p-4 box-border" v-show="showAdvancedSettings">
                <!-- 启用按钮 -->
                <!--                <div class="mb-4">-->
                <!--                    <label class="form-label">启用状态</label>-->
                <!--                    <el-switch class="ml-[10px]"-->
                <!--                               v-model="apiConfig_form.publishStatus"-->
                <!--                               active-value="1"-->
                <!--                               inactive-value="0"-->
                <!--                               active-text="已启用"-->
                <!--                               inactive-text="已禁用">-->
                <!--                    </el-switch>-->
                <!--                </div>-->
                <!-- API输出格式设置 -->
                <div class="mb-4">
                    <label class="form-label">API输出格式设置</label>
                    <el-input type="textarea" v-model="apiConfig_form.responseFormatPrompt"
                              class="form-control sysPrompt"
                              placeholder="目前仅支持json格式的数据设置"></el-input>
                </div>
            </div>
        </div>

        <div class="config-card box-border px-4 py-2">
            <el-button type="primary" size="small" @click="handleSaveConf">保存</el-button>
        </div>

        </div> <!-- 关闭 config-content -->
        <th:block th:replace="~{fragments/robot-detail/plugin-modal::plugin-modal}"></th:block>
        
        <!-- 插件组模态框 -->
        <th:block th:replace="~{fragments/robot-detail/plugin-group-modal::plugin-group-modal}"></th:block>
    </div>


    <script>
        var vue_detail_conf = new Vue({
            el: '#detail_conf',
            data: {
                // 控制高级设置显示/隐藏
                showAdvancedSettings: false,
                // 模型配置卡片默认展开
                isModelConfigExpanded: true,
                // 插件卡片默认收起
                isPluginConfigExpanded: true,
                // 插件组卡片默认展开
                isPluginGroupConfigExpanded: true,
                apiConfig_form: {
                    id: apiConfig.id || '',
                    responseFormatPrompt: apiConfig.responseFormatPrompt || '',
                    // publishStatus: apiConfig.publishStatus || 0,
                    agentShowTitle: apiConfig.agentShowTitle || '',
                },
                config_form: {
                    agentId: agent.id,
                    agentName: agent.agentName,
                    welcomeMsg: agent.welcomeMsg || '',
                    aiModelId: agent.aiModelId || '',
                    aiModelName: agent.aiModelName || '',
                    aiSysPromptText: agent.aiSysPromptText || '',
                    configParam: {},
                    // 模型配置
                    aiConfig: {}, //供前端渲染
                    aiConfigStr: agent.aiConfig || '',
                    // 开场问题配置
                    openingQuestionsEnabled: false,
                    openingQuestions: ['']
                },
                aiConfig_default: {
                    dialogsNum: 10,
                    voiceInputStatus: 0
                },
                rawAiConfig: agent.aiConfig || '',
                config_modelGroupList: modelGroupList,

                plugin_form: {
                    visible: false,
                    agentId: agent.id,
                    agentName: agent.agentName,
                    pluginName: '',
                    pluginType: '',
                    pluginDesc: ''
                },

                // 插件弹框
                activeTab: 'all',
                // 插件列表
                pluginList: [],
                // 搜索文本
                pluginSearchText: '',
                // 已添加的插件列表
                addedPlugins: [],

                // === 插件组相关数据 ===
                plugin_group_form: {
                    visible: false,
                    agentId: agent.id,
                    agentName: agent.agentName
                },

                // 插件组弹框
                pluginGroupActiveTab: 'all',
                // 插件组列表
                pluginGroupList: [],
                // 插件组搜索文本
                pluginGroupSearchText: '',
                // 已添加的插件组列表
                addedPluginGroups: [],
                // 已绑定的插件组
                boundPluginGroups: [],
            },
            computed: {
                // 过滤后的插件列表
                filteredPluginList() {
                    if (!this.pluginSearchText) {
                        return this.pluginList;
                    }
                    const searchText = this.pluginSearchText.toLowerCase();
                    return this.pluginList.filter(plugin => 
                        (plugin.pluginLabel || plugin.pluginName || '').toLowerCase().includes(searchText) ||
                        (plugin.pluginDesc || '').toLowerCase().includes(searchText) ||
                        (plugin.pluginCategoryName || '').toLowerCase().includes(searchText)
                    );
                },
                // 是否可以添加插件
                canAddPlugin() {
                    return true; // 插件选择后即可添加
                },

                // === 插件组相关计算属性 ===
                // 过滤后的插件组列表
                filteredPluginGroupList() {
                    if (!this.pluginGroupSearchText) {
                        return this.pluginGroupList;
                    }
                    const searchText = this.pluginGroupSearchText.toLowerCase();
                    return this.pluginGroupList.filter(group => 
                        (group.groupName || '').toLowerCase().includes(searchText) ||
                        (group.groupDesc || '').toLowerCase().includes(searchText) ||
                        (group.groupTypeName || '').toLowerCase().includes(searchText)
                    );
                }
            },
            created: function () {
                // 初始化时双向绑定
                this.config_form.aiConfig = this.parseAiConfig(this.rawAiConfig);
                // 初始化开场问题数据
                this.initOpeningQuestions();
                // 加载已添加的插件
                this.loadAddedPlugins();
                // 加载已添加的插件组
                this.loadAddedPluginGroups();
            },
            methods: {
                // 数据解析方法
                parseAiConfig(config) {
                    try {
                        return typeof config === 'string' ? JSON.parse(config) : config;
                    } catch {
                        // 默认值
                        return this.aiConfig_default;
                    }
                },
                
                // 初始化开场问题数据
                initOpeningQuestions() {
                    try {
                        if (agent.openingQuestions && agent.openingQuestions !== '' && agent.openingQuestions !== '[]') {
                            var questions = typeof agent.openingQuestions === 'string' 
                                ? JSON.parse(agent.openingQuestions) 
                                : agent.openingQuestions;
                            // 过滤空字符串
                            var validQuestions = questions.filter(function(q) {
                                return q && q.trim() !== '';
                            });
                            this.config_form.openingQuestions = validQuestions.length > 0 ? validQuestions : [''];
                        } else {
                            this.config_form.openingQuestions = [''];
                        }
                        this.config_form.openingQuestionsEnabled = agent.openingQuestionsEnabled || false;
                    } catch (e) {
                        console.error('Failed to parse opening questions:', e);
                        this.config_form.openingQuestions = [''];
                        this.config_form.openingQuestionsEnabled = false;
                    }
                },

                // 语音输入处理
                handleSwitchChange(val) {
                    this.config_form.aiConfig.voiceInputStatus = val ? 1 : 0;
                    this.rawAiConfig = JSON.stringify(this.config_form.aiConfig);
                },
                // 滑块变化处理
                handleSliderChange(val) {
                    this.config_form.aiConfig.dialogsNum = val;
                    this.rawAiConfig = JSON.stringify(this.config_form.aiConfig);
                },
                // 模型设置 展开收起
                toggleModelConfig: function () {
                    this.isModelConfigExpanded = !this.isModelConfigExpanded;
                },
                // 高级设置 展开收起
                toggleAdvancedSettings: function () {
                    this.showAdvancedSettings = !this.showAdvancedSettings;
                },
                // 插件卡片收起展示
                togglePluginConfig() {
                    this.isPluginConfigExpanded = !this.isPluginConfigExpanded;
                },
                
                // 开场问题相关方法
                handleOpeningQuestionsToggle(val) {
                    this.config_form.openingQuestionsEnabled = val;
                    if (val) {
                        // 开启时，如果没有问题或只有空问题，初始化一个空问题
                        var hasValidQuestions = this.config_form.openingQuestions.some(function(q) {
                            return q && q.trim() !== '';
                        });
                        if (!hasValidQuestions || this.config_form.openingQuestions.length === 0) {
                            this.config_form.openingQuestions = [''];
                        }
                    }
                },
                
                addOpeningQuestion() {
                    if (this.config_form.openingQuestions.length < 3) {
                        this.config_form.openingQuestions.push('');
                    }
                },
                
                removeOpeningQuestion(index) {
                    if (this.config_form.openingQuestions.length > 1) {
                        this.config_form.openingQuestions.splice(index, 1);
                    }
                },
                handleSaveConf: function () {
                    this.config_form.configParam = {...this.apiConfig_form} || {};
                    this.config_form.aiConfigStr = this.rawAiConfig;
                    
                    // 处理开场问题数据
                    if (this.config_form.openingQuestionsEnabled) {
                        // 过滤空的问题
                        var validQuestions = this.config_form.openingQuestions.filter(function(q) {
                            return q && q.trim() !== '';
                        });
                        this.config_form.openingQuestions = JSON.stringify(validQuestions);
                    } else {
                        this.config_form.openingQuestions = JSON.stringify([]);
                    }
                    
                    console.log('this.config_form->', this.config_form)
                    var f = this.config_form || {}
                    // console.log('f->', this.config_form.configParam)
                    if (!f.agentName) return this.$message('系统异常，助手名称获取异常！');
                    if (!f.aiModelId) return this.$message('请先选择模型！');
                    // f.aiModelName = (modelList.find(el => el.id == f.aiModelId) || {}).modelName
                    f.aiModelName = (es5_find(modelList, function (item) {
                        return item.id === f.aiModelId;
                    }) || {}).modelName;
                    api_robot_update(f, function (res) {
                        if (res.code === 200) {
                            this.$message.success('配置保存成功');
                            // 更新预览区域
                            if (typeof vue !== 'undefined') {
                                if (vue.updateOpeningQuestions) {
                                    vue.updateOpeningQuestions();
                                }
                                if (vue.updateWelcomeMessage) {
                                    vue.updateWelcomeMessage(f.welcomeMsg);
                                }
                            }
                        } else {
                            this.$message.error('配置保存失败: ' + res.message);
                        }
                    }.bind(this))
                },
                handleAddPluginOne: function () {
                    // 重置表单
                    this.plugin_form.pluginName = '';
                    this.plugin_form.pluginType = '';
                    this.plugin_form.pluginDesc = '';
                    this.pluginSearchText = '';
                    this.activeTab = 'builtin';
                    
                    // 显示弹窗
                    this.plugin_form.visible = true;
                    
                    // 获取插件列表
                    var params = {
                        agentId: agent.id
                    };
                    api_plugin_list(params, function (res) {
                        if (res.code === 200) {
                            console.log("res.data", res.data)
                            this.pluginList = res.data;
                        } else {
                            console.error("Failed to load plugins:", res.message);
                            this.$message.error('加载插件列表失败: ' + res.message);
                        }
                    }.bind(this));
                },


                // 加载已添加的插件
                loadAddedPlugins() {
                    api_agent_plugins(agent.id, function (res) {
                        if (res.code === 200) {
                            this.addedPlugins = res.data || [];
                        } else {
                            console.error("Failed to load agent plugins:", res.message);
                            this.addedPlugins = [];
                        }
                    }.bind(this));
                },

                // 选择插件
                selectPlugin(plugin) {
                    // 检查是否已绑定
                    if (plugin.isBound) {
                        this.$message.warning('该插件已绑定');
                        return;
                    }
                    
                    // 绑定插件到智能体
                    var bindRequest = {
                        agentId: agent.id,
                        agentCode: agent.agentCode,
                        pluginId: plugin.id,
                        pluginCode: plugin.pluginCode,
                        priority: 0,
                        enabled: 1
                    };
                    
                    api_plugin_bind(bindRequest, function (res) {
                        if (res.code === 200) {
                            this.$message.success('插件绑定成功');
                            this.plugin_form.visible = false;
                            // 刷新已添加插件列表
                            this.loadAddedPlugins();
                            // 重新加载插件列表以更新绑定状态
                            this.handleAddPluginOne();
                        } else {
                            this.$message.error('插件绑定失败: ' + res.message);
                        }
                    }.bind(this));
                },



                // 获取插件类型图标
                getPluginIcon(pluginType) {
                    switch(pluginType) {
                        case 2: // MCP
                        case 'mcp':
                            return 'el-icon-cpu';
                        case 3: // 内置
                        case 'builtin':
                            return 'el-icon-setting';
                        default:
                            return 'el-icon-cpu';
                    }
                },
                
                // 获取插件类型标签颜色
                getPluginTypeTagType(pluginType) {
                    switch(pluginType) {
                        case 2: // MCP
                        case 'mcp':
                            return 'primary';
                        case 3: // 内置
                        case 'builtin':
                            return 'warning';
                        default:
                            return 'info';
                    }
                },
                
                // 根据类型过滤插件
                getPluginsByType(pluginType) {
                    if (!this.pluginList) return [];
                    
                    let filteredList = this.pluginList.filter(plugin => plugin.pluginType == pluginType);
                    
                    // 如果有搜索文本，再进行搜索过滤
                    if (this.pluginSearchText) {
                        const searchText = this.pluginSearchText.toLowerCase();
                        filteredList = filteredList.filter(plugin => 
                            (plugin.pluginLabel || plugin.pluginName || '').toLowerCase().includes(searchText) ||
                            (plugin.pluginDesc || '').toLowerCase().includes(searchText) ||
                            (plugin.pluginCategoryName || '').toLowerCase().includes(searchText)
                        );
                    }
                    
                    return filteredList;
                },

                // 处理插件操作
                handlePluginAction(command) {
                    if (command.action === 'edit') {
                        this.editPlugin(command.plugin);
                    } else if (command.action === 'delete') {
                        this.deletePlugin(command.plugin);
                    }
                },

                // 编辑插件
                editPlugin(plugin) {
                    this.$message.info('编辑功能开发中...');
                },

                // 删除插件
                deletePlugin(plugin) {
                    this.$confirm('确定要解绑这个插件吗？', '确认解绑', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        api_plugin_unbind(agent.id, plugin.id, function (res) {
                            if (res.code === 200) {
                                this.$message.success('插件解绑成功');
                                // 刷新已添加插件列表
                                this.loadAddedPlugins();
                            } else {
                                this.$message.error('插件解绑失败: ' + res.message);
                            }
                        }.bind(this));
                    }).catch(() => {
                        // 取消删除
                    });
                },

                // 确认添加插件
                handleConfirmAddPlugin() {
                    this.$message.warning('请先选择一个插件');
                    return;
                },

                // === 插件组相关方法 ===

                // 切换插件组配置展开状态
                togglePluginGroupConfig() {
                    this.isPluginGroupConfigExpanded = !this.isPluginGroupConfigExpanded;
                },

                // 添加插件组按钮点击
                handleAddPluginGroupOne() {
                    this.plugin_group_form.visible = true;
                    this.loadPluginGroupList();
                },

                // 加载插件组列表
                loadPluginGroupList() {
                    api_plugin_group_list({ agentId: agent.id }, function(res) {
                        if (res.code === 200) {
                            this.pluginGroupList = res.data || [];
                        } else {
                            this.$message.error('加载插件组列表失败: ' + res.message);
                        }
                    }.bind(this));
                },

                // 加载已添加的插件组
                loadAddedPluginGroups() {
                    api_agent_plugin_groups(agent.id, function(res) {
                        if (res.code === 200) {
                            this.addedPluginGroups = res.data || [];
                            this.boundPluginGroups = res.data || [];
                        } else {
                            console.error('加载插件组失败:', res.message);
                        }
                    }.bind(this));
                },

                // 绑定插件组
                bindPluginGroup(group) {
                    const params = {
                        agentId: agent.id,
                        agentCode: agent.agentCode,
                        pluginGroupId: group.id,
                        groupCode: group.groupCode,
                        priority: group.priority || 0,
                        enabled: 1
                    };

                    api_plugin_group_bind(params, function(res) {
                        if (res.code === 200) {
                            this.$message.success('插件组绑定成功');
                            // 刷新列表
                            this.loadPluginGroupList();
                            this.loadAddedPluginGroups();
                        } else {
                            this.$message.error('插件组绑定失败: ' + res.message);
                        }
                    }.bind(this));
                },

                // 解绑插件组
                unbindPluginGroup(group) {
                    this.$confirm('确定要移除这个插件组吗？移除后将失去该组内所有插件功能。', '确认移除', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        api_plugin_group_unbind(agent.id, group.id, function(res) {
                            if (res.code === 200) {
                                this.$message.success('插件组移除成功');
                                // 刷新列表
                                this.loadPluginGroupList();
                                this.loadAddedPluginGroups();
                            } else {
                                this.$message.error('插件组移除失败: ' + res.message);
                            }
                        }.bind(this));
                    }).catch(() => {
                        // 取消删除
                    });
                },

                // 更新插件组优先级
                updatePluginGroupPriority(group) {
                    const params = {
                        agentId: agent.id,
                        agentCode: agent.agentCode,
                        pluginGroupId: group.id,
                        groupCode: group.groupCode,
                        priority: group.priority,
                        enabled: 1
                    };

                    api_plugin_group_update(params, function(res) {
                        if (res.code === 200) {
                            this.$message.success('优先级更新成功');
                        } else {
                            this.$message.error('优先级更新失败: ' + res.message);
                        }
                    }.bind(this));
                },

                // 处理插件组操作
                handlePluginGroupAction(command) {
                    if (command.action === 'config') {
                        this.configPluginGroup(command.group);
                    } else if (command.action === 'delete') {
                        this.unbindPluginGroup(command.group);
                    }
                },

                // 配置插件组
                configPluginGroup(group) {
                    this.$message.info('插件组配置功能开发中...');
                },

                // 保存插件组配置
                savePluginGroupConfig() {
                    this.plugin_group_form.visible = false;
                    this.$message.success('插件组配置已保存');
                },

                // 获取插件组图标
                getPluginGroupIcon(groupType) {
                    switch(groupType) {
                        case 1: return 'fa-tools';
                        case 2: return 'fa-chart-line';
                        case 3: return 'fa-cogs';
                        default: return 'fa-puzzle-piece';
                    }
                },

                // 获取插件组类型Tag类型
                getPluginGroupTypeTagType(groupType) {
                    switch(groupType) {
                        case 1: return 'primary';
                        case 2: return 'warning';
                        case 3: return 'success';
                        default: return '';
                    }
                },

                // 获取模型能力图标
                getModelCapabilityIcons(model) {
                    var icons = [];
                    
                    try {
                        // 解析 supported_capability 字段
                        if (model.supportedCapability) {
                            var supportedCapability = typeof model.supportedCapability === 'string' 
                                ? JSON.parse(model.supportedCapability) 
                                : model.supportedCapability;
                            
                            // 图片识别能力
                            if (supportedCapability.image_recognition === true) {
                                icons.push({
                                    key: 'image_recognition',
                                    icon: 'el-icon-view',
                                    class: 'image-recognition-icon',
                                    tooltip: '支持图片识别'
                                });
                            }
                            
                            // 插件支持能力
                            if (supportedCapability.plugin_support === true) {
                                icons.push({
                                    key: 'plugin_support',
                                    icon: 'el-icon-cpu',
                                    class: 'plugin-support-icon',
                                    tooltip: '支持插件执行'
                                });
                            }
                        } else {
                            // 兼容旧的字段
                            if (model.supportImageRecognition === true) {
                                icons.push({
                                    key: 'image_recognition',
                                    icon: 'el-icon-view',
                                    class: 'image-recognition-icon',
                                    tooltip: '支持图片识别'
                                });
                            }
                        }
                        
                    } catch (e) {
                        console.error('解析模型能力配置失败:', e);
                        // 降级到旧字段
                        if (model.supportImageRecognition === true) {
                            icons.push({
                                key: 'image_recognition',
                                icon: 'el-icon-view',
                                class: 'image-recognition-icon',
                                tooltip: '支持图片识别'
                            });
                        }
                    }
                    
                    return icons;
                },

                // 显示tooltip
                showTooltip: function(event) {
                    var target = event.target.closest('.capability-icon');
                    var rect = target.getBoundingClientRect();
                    var tooltip = target.querySelector('::before');
                    
                    // 计算tooltip位置 - 显示在图标上方
                    var tooltipTop = rect.top - 35; // 图标上方35px
                    var tooltipLeft = rect.left + (rect.width / 2);
                    
                    // 设置CSS自定义属性
                    target.style.setProperty('--tooltip-top', tooltipTop + 'px');
                    target.style.setProperty('--tooltip-left', tooltipLeft + 'px');
                    
                    target.classList.add('tooltip-visible');
                },

                // 隐藏tooltip
                hideTooltip: function(event) {
                    var target = event.target.closest('.capability-icon');
                    target.classList.remove('tooltip-visible');
                }
            }
        })
    </script>

</th:block>

</body>
</html>